import React, {Component} from 'react';
import {View, Image, StyleSheet, Text, AppState, ScrollView, AppStateStatus, TouchableHighlight, TouchableOpacity} from 'react-native';

import { connect } from 'react-redux';
import {TABBAR_LABEL, ROUTERMAP, Global} from '../util/constants';
import Swiper from '../components/Swiper';
import { scaleSize, scaleFontSize } from '../util/size';
import MarketItems from '../components/MarketItems';
import icons from '../util/icons';

import { IReduxUserInfo , INavigation, IReduxMarketInfo, IReduxMarketItem} from '../interface';
// import { subscribeCoinxpMarket, closeCoinxpMarket } from '../util/socket';
import * as marketAction from '../actions/market';
import { utilGetMarketInfoByCoinType } from '../util/marketUtil';
import { initMarketWS } from '../util/marketSocket';

const menuData = [
    {text: '行情', img: icons.homeMarket, router: ROUTERMAP.market},
    {text: '交易', img: icons.homeExchange, router: ROUTERMAP.transaction},
    {text: '持仓', img: icons.homeBalance, router: ROUTERMAP.balance},
    {text: '充币', img: icons.homeDeposit, router: ROUTERMAP.deposit},
    {text: '资讯', img: icons.homeNews},
    {text: '社区', img: icons.homeCommunity},
    {text: '入门', img: icons.homeStart},
    {text: '客服', img: icons.homeCustom},
];

interface IProps {
    user: IReduxUserInfo,
    navigation: INavigation,
    updateMarketData: Function,
    updateOneMarketItem: Function,
    marketInfo: IReduxMarketInfo,
    updateAmountTo: number,
}

interface IState {
    currentAppState: AppStateStatus
}


class PublicView extends Component<IProps, IState>{
    
    constructor (props) {
        super(props);
        this.state = {
            currentAppState: 'active',
        }
    }

    static navigationOptions = {
        tabBarLabel: TABBAR_LABEL.home,
        tabBarIcon: ({ focused, tintColor }) => {
            if (focused) {
                return (
                    <Image source={icons.tabHomeO} style={Global.tabIconStyles}/>
                );
            }
            return (
                <Image source={icons.tabHome} style={Global.tabIconStyles}/>
            );
        },

    };

    componentDidMount() {
        AppState.addEventListener('change', this.handleAppStateChange);
        // setInterval(this.testForGeneratorMarketData, 2000);
        // initMarketWS((err, res) => {
        //     console.log('initMarketWs', res);
        // })
        initMarketWS((err, res) => {
            // console.log('initMarket...ws', res);
            if (res) {
                this.props.updateOneMarketItem(res);
            }
        })
    }

    /**
     * 监听 APP 状态，在这里
     */
    handleAppStateChange = (nextAppState: AppStateStatus) => {
        this.setState({currentAppState: nextAppState});
        console.log('nextAppState --- -- - -- ', nextAppState);
        // if (nextAppState === 'active') {
        //     subscribeCoinxpMarket((_, topOrderData) => {
        //         console.log('topOrderData', topOrderData);
        //     });
        // } else if (nextAppState === 'background') {
        //     closeCoinxpMarket();

        // }
    }

    turnToPage = (pageName: string, params?: Object) => {
        this.props.navigation.navigate(pageName, params);
    };


    renderMenu = () => {
        
        let dataLineOne = menuData.slice(0, 4);
        let dataLineTwo = menuData.slice(4, 8);
        return (
            <View style={{display: 'flex', flexDirection: 'column', height: 169, marginTop: 11, padding: 23, paddingBottom: 27, backgroundColor: '#FFFFFF'}}>

                    <View style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-between'}}>
                        {
                            dataLineOne.map((v, index) => {
                                return (
                                    <TouchableOpacity activeOpacity={1} key={`menu-${index}`} onPress={() => {
                                        if (v.router) {
                                            this.turnToPage(v.router);
                                        }
                                    }}>
                                        <View style={{
                                            display: 'flex',
                                            flexDirection: 'column',
                                            width: scaleSize(34), 
                                            alignItems: 'center',
                                        }}
                                            key={`dataLineOne-${index}`}>
                                            <Image style={{
                                                width: scaleSize(34),
                                                height: scaleSize(34),
                                                borderRadius: scaleSize(17),
                                            }} source={v.img} />
                                            <Text style={{
                                                textAlign: 'center',
                                                lineHeight: scaleSize(17),
                                                height: scaleSize(17),
                                                fontFamily: 'PingFangSC-Regular',
                                                fontSize: scaleFontSize(12),
                                                color: '#4869EE',
                                                marginTop: scaleSize(2),
                                            }}>{v.text}</Text>
                                        </View>
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </View>
                <View style={{display: 'flex', flexDirection: 'row', marginTop: 31, justifyContent: 'space-between'}}>
                    {
                        dataLineTwo.map((v, index) => {
                            return (
                                <TouchableOpacity key= {`dataLine2-${index}`} activeOpacity={1} onPress={() => {
                                    if (v.router) {
                                        this.turnToPage(v.router);
                                    }
                                }}>
                                <View style={{
                                    display: 'flex',
                                    flexDirection: 'column',
                                    width: scaleSize(34),
                                    alignItems: 'center',
                                }} 
                                    key={`dataLineTwo-${index}`}>
                                    <Image style={{
                                        width: scaleSize(34),
                                        height: scaleSize(34),
                                        borderRadius: scaleSize(17),
                                    }} source={v.img}/>
                                    <Text style={{
                                        textAlign: 'center',
                                        height: scaleSize(17),
                                        lineHeight: scaleSize(17),
                                        fontFamily: 'PingFangSC-Regular',
                                        fontSize: scaleFontSize(12),
                                        color: '#4869EE',
                                        marginTop: scaleSize(2),
                                    }}>{v.text}</Text>
                                </View>
                            </TouchableOpacity>
                            )
                        })
                    }
                </View>
            </View>
        )
    };

    initStr = () => {
        let str = 'QAZWSXEDCRFVTGBYHNUJMIKOLP';
        let res = '';
        for(let i = 0; i < 4; i ++) {
            res += str[Math.floor(Math.random() * str.length)];
        }
        return res;
    }

    initExtent = () => {
        // for(let i = 0; i < )
        let extent = Math.floor(Math.random() * 10);
        let str = extent > 5 ? '-': '';
        str += (Math.floor(Math.random() * 10) + '.' + Math.floor(Math.random() * 100) + '%')
        return str;
    }

    render() {
        let marketInfo = this.props.marketInfo;
        return (
            <ScrollView style={styles.container}>
            <View style={styles.swiper}>
                <Swiper/>
            </View>
            {
                this.renderMenu()
            }

            <View style={{marginTop: 10}}>
                <MarketItems keyV={'home-market'} navigation={this.props.navigation}
                data = {utilGetMarketInfoByCoinType(marketInfo, 'all')}
                marketInfo={marketInfo}
                />
            </View>
            </ScrollView>
        )
    }
}

export default connect(
    (state) => ({
        user: state.user,
        marketInfo: state.market,
    }),
    (dispatch) => ({
        updateMarketData: (data) => dispatch(marketAction.updateMarketData(data)),
        updateAmountTo: (data) => dispatch(marketAction.updateAmountTo(data)),
        updateOneMarketItem: (data) => dispatch(marketAction.updateOneMarketItem(data)),
    })
)(PublicView);

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
    },
    swiper: {
        height: scaleSize(188)
    },
    tip: {
        height:30,
    },
    homeTrade: {
        height: 260
    }
})